use std::time::{SystemTime, UNIX_EPOCH};

/// 数据帧结构定义
#[derive(Debug, Clone, PartialEq)]
pub struct DataFrame {
    /// 帧头标识
    pub header: u8,
    /// 设备地址
    pub device_addr: u8,
    /// 命令码
    pub cmd: u8,
    /// 数据长度
    pub data_len: usize,
    /// 数据内容
    pub data: Vec<u8>,
    /// 校验和
    pub checksum: u8,
    /// 帧尾标识
    pub footer: u8,
    /// 接收时间戳(毫秒)
    pub timestamp: u64,
}

impl DataFrame {
    /// 获取当前时间戳(毫秒)
    pub fn get_timestamp_ms() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0)
    }
}

/// 解析状态
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ParseState {
    WaitingForHeader,
    ReadingDeviceAddr,
    ReadingCmd,
    ReadingDataLen,
    ReadingData(usize),
    ReadingChecksum,
    ReadingFooter,
}

/// 数据处理结果
#[derive(Debug)]
pub enum ProcessResult {
    /// 成功解析并处理
    Success(DataFrame),
    /// 解析错误
    ParseError(String),
    /// 校验错误
    ChecksumError { calculated: u8, received: u8 },
    /// 不支持的命令
    UnsupportedCommand(u8),
}

/// 数据处理器配置
#[derive(Debug, Clone)]
pub struct DataProcessorConfig {
    /// 帧头标识
    pub frame_header: u8,
    /// 帧尾标识
    pub frame_footer: u8,
    /// 最大数据长度
    pub max_data_length: usize,
    /// 是否启用校验和
    pub enable_checksum: bool,
}

impl Default for DataProcessorConfig {
    fn default() -> Self {
        DataProcessorConfig {
            frame_header: 0xAA,  // 帧头默认值
            frame_footer: 0x55,  // 帧尾默认值
            max_data_length: 1024,
            enable_checksum: true,
        }
    }
}
